import request from '@/utils/request'
import type { Contract } from '@/types'
import { mockContractAPI } from '@/mock/api'

// 是否启用Mock模式
const ENABLE_MOCK = import.meta.env.VITE_ENABLE_MOCK !== 'false'

// 获取合同列表
export const getContractList = (params: any) => {
  if (ENABLE_MOCK) {
    return mockContractAPI.getList(params)
  }
  return request({
    url: '/contract/list',
    method: 'get',
    params
  })
}

// 获取合同详情
export const getContractDetail = (id: string) => {
  if (ENABLE_MOCK) {
    return mockContractAPI.getDetail(id)
  }
  return request({
    url: `/contract/${id}`,
    method: 'get'
  })
}

// 创建合同
export const createContract = (data: Partial<Contract>) => {
  if (ENABLE_MOCK) {
    return mockContractAPI.create(data)
  }
  return request({
    url: '/contract',
    method: 'post',
    data
  })
}

// 更新合同
export const updateContract = (id: string, data: Partial<Contract>) => {
  if (ENABLE_MOCK) {
    return mockContractAPI.update(id, data)
  }
  return request({
    url: `/contract/${id}`,
    method: 'put',
    data
  })
}

// 删除合同
export const deleteContract = (id: string) => {
  if (ENABLE_MOCK) {
    return mockContractAPI.delete(id)
  }
  return request({
    url: `/contract/${id}`,
    method: 'delete'
  })
}

// 更新合同状态
export const updateContractStatus = (id: string, status: string) => {
  if (ENABLE_MOCK) {
    return mockContractAPI.update(id, { status })
  }
  return request({
    url: `/contract/${id}/status`,
    method: 'put',
    data: { status }
  })
}

// 获取合同模板
export const getContractTemplates = () => {
  if (ENABLE_MOCK) {
    return mockContractAPI.getTemplates()
  }
  return request({
    url: '/contract/templates',
    method: 'get'
  })
}

// 生成合同
export const generateContract = (templateId: string, data: any) => {
  if (ENABLE_MOCK) {
    return Promise.resolve({
      code: 200,
      data: { contractId: 'generated-' + Date.now() },
      message: '合同生成成功'
    })
  }
  return request({
    url: '/contract/generate',
    method: 'post',
    data: { templateId, data }
  })
}
